/*
 * brokerConector.cpp
 *
 *  Created on: 21/07/2014
 *      Author: nicolas
 */

#include "../defines.h"
#include "../ipc/Socket.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sstream>
#include <syslog.h>
#include <sys/types.h>
#include <signal.h>
#include <string.h>

using namespace std;

void sig_handler(int signo) {
	char mostrar[80];
	sprintf(mostrar, "Salida por borrado de cola\n");
	write(fileno(stdout), mostrar, strlen(mostrar));
}

int main(int argc, char **argv) {

	if (argc != 2) {
		exit(1);
	}

	int port = atoi(argv[1]);

	char encabezado[80];
	sprintf(encabezado, "BrokerConector");
	openlog(encabezado, LOG_PID | LOG_CONS, LOG_LOCAL0);

	struct sigaction sa;
	memset(&sa, 0, sizeof(sa));
	sa.sa_handler = &sig_handler;
	sigaction(SIGUSR1, &sa, NULL);

	Socket socket;
	stringstream fd;

	socket.bindTo(port);
	socket.listenTo(10);

	bool salir = false;

	while (!salir) {
		int sockFd = socket.acceptFrom();
		if (sockFd == -1)
			exit(1);

		syslog(LOG_INFO, "Recibio conceccion socket: %i", sockFd);

		int pid = fork();
		if (pid == 0) {
			fd << sockFd;
			socket.closeSock();
			execlp("./brokerComunicator", "BrokerComunicator", fd.str().c_str(),
					NULL);
			perror("Error en el exec comunicator");
			exit(1);
		}
		Socket nuevo(sockFd);
		nuevo.closeSock();

	}

	socket.closeSock();
}

